package com.ok.common.ext

import android.content.Context
import android.content.pm.PackageManager
import android.os.PowerManager
import android.view.WindowManager
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

fun Context.getColors(@ColorRes id: Int) = ContextCompat.getColor(this, id)

fun Fragment.getColors(@ColorRes id: Int) = ContextCompat.getColor(context!!, id)

fun Context.getDrawables(@DrawableRes id: Int) = ContextCompat.getDrawable(this, id)

fun Context.acquire(tag: String): PowerManager.WakeLock {
    val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
    val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::$tag").apply {
        acquire()
    }
    return wakeLock
}

/**
 * 扩展PowerManager.WakeLock以释放WakeLock。
 */
fun PowerManager.WakeLock.release() {
    if (this.isHeld) {
        this.release()
    }
}

fun FragmentActivity.keepScreenOn() {
    this.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

fun FragmentActivity.clearScreenOn() {
    this.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

fun Context.versionName(): String {
    try {
        val packageInfo = packageManager.getPackageInfo(packageName, 0)
        return packageInfo.versionName?:""
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return ""
}

fun Context.versionCode(): Int {
    try {
        val packageInfo = packageManager.getPackageInfo(packageName, 0)
        return packageInfo.versionCode
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return -1
}